import json
import random
import time
import uuid

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from function_scheduling_distributed_framework import task_deco, BrokerEnum, timing_publish_deco, \
    fsdf_background_scheduler

from app.models import Card, Registration
from datetime import datetime
from app.ResultTools import ResultTools

# 中国历史上著名的神医
doctorList = ['扁鹊', '李时珍', '华佗', '孙思邈', '张仲景', '葛洪', '皇甫谧', '王叔和', '钱乙', '淳于意']
adviceList = [
    '给予手法复位，复位可进行多次，还可给予抗眩晕、抗焦虑、镇静、对症治疗。梅尼埃病可给予高压氧治疗，并辅以脱水、扩血管治疗，必要时可使用糖皮质激素。',
    '精神压力大，可能会出现这种情况，伴随的其他表现为焦虑、烦躁、睡眠不足、易疲劳、注意力不集中等。这种情况注意休息和睡眠往往可以自行缓解，良好的心态是关键。',
    '把你的手浸入一盆热水中（保持水温在60摄氏度左右），通常30分钟左右，头痛就会减轻或消失。这是因为偏头痛是由脑血管充血和脑神经压迫引起的。',
    '1、服用非甾体抗炎药止痛处理，2、可适当进行头部按摩，放松颞肌、额肌等肌群。3、避免可能导致头痛的食物，如酒精，奶酪，咖啡等。4、就诊医院，查明头痛的病因，对因治疗。',
    '当出现头痛时，不必过度惊慌，应冷静面对病情，可按上述方式处理。但需明白止痛治疗只是治标，不是治本，应及时就诊医院，完善颅脑ct或者磁共振检查，明确病因，对因治疗。']


@task_deco('seeDoctor', broker_kind=BrokerEnum.LOCAL_PYTHON_QUEUE)
def seeDoctor(RegistrationId):
    registration = Registration.objects.filter(id=RegistrationId).first()
    if not registration:
        print("就诊失败！挂号记录不存在！" + RegistrationId)
        return

    registration.doctor = random.choice(doctorList)
    registration.advice = random.choice(adviceList)
    registration.save()


# 启动定时
fsdf_background_scheduler.start()
seeDoctor.consume()


def selectOneByPhone(phone):
    return Card.objects.filter(phone=phone).first()


def register(request):
    phone = request.POST.get('phone')
    password = request.POST.get('password')
    name = request.POST.get('name')
    if not (phone and password and name):
        return ResultTools.error("表单不能为空！")

    card = selectOneByPhone(phone)
    if card:
        return ResultTools.error("账号已存在！")

    card = Card()
    card.cardid = uuid.uuid4().hex
    card.phone = phone
    card.password = password
    card.name = name
    card.createtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    card.save()
    return ResultTools.ok({
        "cardid": card.cardid,
        "name": card.name,
        "phone": card.phone,
        "password": card.password,
        "createtime": card.createtime,
        "deletetime": card.deletetime
    })


def login(request):
    phone = request.POST.get('phone')
    password = request.POST.get('password')
    if not (phone and password):
        return ResultTools.error("手机号或密码为空！")

    card = Card.objects.filter(phone=phone).first()
    if not card:
        return ResultTools.error("账号不存在！")
    if card.deletetime:
        return ResultTools.error("账号已被删除！")

    if card.password != password:
        return ResultTools.error("密码不正确！")

    return ResultTools.ok({
        "cardid": card.cardid,
        "name": card.name,
        "phone": card.phone,
        "password": card.password,
        "createtime": card.createtime,
        "deletetime": card.deletetime
    })


def getCardInfo(request):
    cardid = request.GET.get('cardid')
    if not cardid:
        return ResultTools.error("表单不能为空！")

    phone = request.headers.get('phone')
    password = request.headers.get('password')
    if not (phone and password):
        return ResultTools.relogin("手机号或密码为空！")

    card = Card.objects.filter(cardid=cardid, phone=phone, password=password, deletetime__isnull=True).first()
    if not card:
        return ResultTools.relogin("账号不存在！")

    return ResultTools.ok({
        "cardid": card.cardid,
        "name": card.name,
        "phone": card.phone,
        "password": card.password,
        "createtime": card.createtime,
        "deletetime": card.deletetime
    })


def delCard(request):
    cardid = request.GET.get('cardid')
    if not cardid:
        return ResultTools.error("表单不能为空！")

    phone = request.headers.get('phone')
    password = request.headers.get('password')
    if not (phone and password):
        return ResultTools.relogin("手机号或密码为空！")

    card = Card.objects.filter(cardid=cardid, phone=phone, password=password, deletetime__isnull=True).first()
    if not card:
        return ResultTools.relogin("账号不存在！")

    card.deletetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    card.save()

    return ResultTools.ok({
        "cardid": card.cardid,
        "name": card.name,
        "phone": card.phone,
        "password": card.password,
        "createtime": card.createtime,
        "deletetime": card.deletetime
    })


def addRegistration(request):
    cardid = request.POST.get('cardid')
    department = request.POST.get('department')
    if not (cardid and department):
        return ResultTools.error("表单不能为空！")

    phone = request.headers.get('phone')
    password = request.headers.get('password')
    if not (phone and password):
        return ResultTools.relogin("手机号或密码为空！")

    card = Card.objects.filter(cardid=cardid, phone=phone, password=password, deletetime__isnull=True).first()
    if not card:
        return ResultTools.relogin("账号不存在！")

    registration = Registration()
    registration.id = uuid.uuid4().hex
    registration.department = department
    registration.cardid = cardid
    registration.createtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    nowTime = time.localtime(time.time() + random.randint(5, 10))
    registration.clinictime = time.strftime('%Y-%m-%d %H:%M:%S', nowTime)
    registration.save()
    fsdf_background_scheduler.add_job(timing_publish_deco(seeDoctor), 'date',
                                      run_date=datetime(nowTime.tm_year, nowTime.tm_mon, nowTime.tm_mday,
                                                        nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec),
                                      args=(registration.id,))  # 定时，只执行一次

    return ResultTools.ok({
        "id": registration.id,
        "cardid": registration.cardid,
        "department": registration.department,
        "doctor": registration.doctor,
        "advice": registration.advice,
        "clinictime": registration.clinictime,
        "createtime": registration.createtime,
        "deletetime": registration.deletetime
    })


def getRegistration(request):
    registrationId = request.GET.get('registrationId')
    if not registrationId:
        return ResultTools.error("表单不能为空！")

    phone = request.headers.get('phone')
    password = request.headers.get('password')
    if not (phone and password):
        return ResultTools.relogin("手机号或密码为空！")

    card = Card.objects.filter(phone=phone, password=password, deletetime__isnull=True).first()
    if not card:
        return ResultTools.relogin("账号不存在！")

    registration = Registration.objects.filter(id=registrationId, deletetime__isnull=True).first()
    if not registration:
        return ResultTools.relogin("就诊记录不存在！")

    return ResultTools.ok({
        "id": registration.id,
        "cardid": registration.cardid,
        "department": registration.department,
        "doctor": registration.doctor,
        "advice": registration.advice,
        "clinictime": registration.clinictime,
        "createtime": registration.createtime,
        "deletetime": registration.deletetime
    })


def getRegistrationList(request):
    cardid = request.GET.get('cardid')

    if not cardid:
        return ResultTools.error("表单不能为空！")

    phone = request.headers.get('phone')
    password = request.headers.get('password')
    if not (phone and password):
        return ResultTools.relogin("手机号或密码为空！")

    card = Card.objects.filter(cardid=cardid, phone=phone, password=password, deletetime__isnull=True).first()
    if not card:
        return ResultTools.relogin("账号不存在！")

    registrationList = Registration.objects.filter(cardid=cardid, deletetime__isnull=True).order_by('-createtime').all()
    if not registrationList:
        return ResultTools.ok([])

    return ResultTools.ok([{
        "id": item.id,
        "cardid": item.cardid,
        "department": item.department,
        "doctor": item.doctor,
        "advice": item.advice,
        "clinictime": item.clinictime,
        "createtime": item.createtime,
        "deletetime": item.deletetime
    } for item in registrationList])


def delRegistration(request):
    registrationId = request.GET.get('registrationId')
    if not registrationId:
        return ResultTools.error("表单不能为空！")

    phone = request.headers.get('phone')
    password = request.headers.get('password')
    if not (phone and password):
        return ResultTools.relogin("手机号或密码为空！")

    card = Card.objects.filter(phone=phone, password=password, deletetime__isnull=True).first()
    if not card:
        return ResultTools.relogin("账号不存在！")

    registration = Registration.objects.filter(id=registrationId, deletetime__isnull=True).first()
    if not registration:
        return ResultTools.relogin("就诊记录不存在！")

    registration.deletetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    registration.save()

    return ResultTools.ok({
        "id": registration.id,
        "cardid": registration.cardid,
        "department": registration.department,
        "doctor": registration.doctor,
        "advice": registration.advice,
        "clinictime": registration.clinictime,
        "createtime": registration.createtime,
        "deletetime": registration.deletetime
    })
